<!-- 智能知识库管理-管理题库以及生成考试试卷 -->
<template>
  <div class="question-bank">
    <el-collapse v-model="activeSections" accordion>
      <!-- 1. 题库查询 -->
      <el-collapse-item title="题库查询" name="query">
        <el-table
          :data="questions"
          border
          stripe
          style="margin-top:16px; width:100%;"
          @selection-change="onSelectionChange"
          v-if = "questions.length"
          ref="questionTable"
          :row-key="id"
          :show-header="true"
        >
          <!-- 勾选列仅在 isSelecting 为 true 时显示 -->
          <el-table-column type="selection" width="55" v-if="isSelecting" />

          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="subject" label="科目" width="100"/>
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">{{ typeLabel(row.type) }}</template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="140"/>
          <el-table-column prop="content" label="内容" />
          <el-table-column prop="score" label="分值" width="80" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>


        <div class="query-form">
          <el-form :inline="true">
            <el-form-item label="页码">
              <el-input-number v-model="pageNum" :min="1" />
            </el-form-item>
            <el-form-item label="每页条数">
              <el-input-number v-model="pageSize" :min="1" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchQuestions">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 编辑题目弹窗 -->
        <el-dialog title="编辑题目" v-model="editDialogVisible" width="600px">
          <el-form :model="editForm" label-width="100px">
            <el-form-item label="科目">
              <el-input v-model="editForm.subject" />
            </el-form-item>
            <el-form-item label="题目类型">
              <el-select v-model="editForm.type" placeholder="请选择">
                <el-option label="填空" :value="0" />
                <el-option label="选择" :value="1" />
                <el-option label="判断" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="editForm.remark" />
            </el-form-item>
            <el-form-item label="内容">
              <el-input type="textarea" :rows="2" v-model="editForm.content" />
            </el-form-item>
            <el-form-item label="分值">
              <el-input-number v-model="editForm.score" :min="0" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveEdit">保存</el-button>
          </template>
        </el-dialog>
      </el-collapse-item>

      <!-- 2. 题目添加 -->
      <el-collapse-item title="题目添加" name="add">
        <div class="add-buttons">
          <el-button
            type="primary"
            :plain="mode==='single'"
            @click="mode='single'"
          >添加单个问题</el-button>
          <el-button
            type="success"
            :plain="mode==='batch'"
            @click="mode='batch'"
          >批量添加问题</el-button>
          <el-button
            type="success"
            :plain="mode==='ai_mode'"
            @click="mode='ai_mode'"
          >AI自动添加问题</el-button>
        </div>
        <div class="add-content">
          <exam-add-one-question v-if="mode==='single'" />
          <knowledge-add-multi-ques v-else-if="mode==='batch'" />
          <div v-else class="ai-area">
            <el-input v-model="AItext" placeholder="输入生成的题目的主题"></el-input>
            <el-button type="success" @click="AIgenerateQuestion">确认添加</el-button>
            <!-- AI生成题目期间悬浮遮罩和缓冲控件 -->
            <div
              v-if="showOverlay"
              class="load-box"
            >
              <div>
              <!-- 圆形缓冲动画 -->
                <div class="loader mb-4"></div>
                <div class="text-gray-700 mb-4">等待…</div>
              </div>
            </div>
          </div>
        </div>
      </el-collapse-item>

      <!-- 3. 生成试卷 -->
      <el-collapse-item title="生成试卷" name="paper">
        <div class="paper-actions">
          <el-button type="warning" @click="startSelecting" v-if="!isSelecting">
            在题库中选择
          </el-button>

          <template v-else>
            <el-input
              :value="selectedIds"
              readonly
              style="width:300px; margin-right:10px;"
              placeholder="已选题目ID"
            />
            <el-button type="info" @click="cancelSelecting">
              取消生成
            </el-button>
            <el-button type="primary" @click="previewDialogVisible = true">
              预览试卷
            </el-button>
          </template>
        </div>
        <!-- 显示生成成功后的试卷编号 -->
        <div v-if="generatedPaperId" style="margin-top:12px; color: #67C23A;">
          已生成试卷编号：<strong>{{ generatedPaperId }}</strong>
        </div>

        <!-- 预览试卷悬浮窗 -->
        <el-dialog
          title="试卷预览"
          v-model="previewDialogVisible"
          width="60%"
          :destroy-on-close="false"
          :close-on-click-modal="false"
          >
          <div class="paper-preview" style="max-height:60vh; overflow-y:auto; padding:16px;">
            <div v-for="(q, idx) in selectedForPaper" :key="q.id" style="margin-bottom:24px;">
              <div style="margin-top:8px;"><strong>{{ idx + 1 }}.</strong>{{ q.content }}</div>
              <div> <em>（分值 {{ q.score }} 分）</em></div>
            </div>
          </div>

          <template #footer>
            <el-button @click="previewDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="generatePaper">确认生成</el-button>
          </template>
        </el-dialog>

        
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import axios from 'axios'
import { useCookies } from 'vue3-cookies'
import ExamAddOneQuestion from '@/components/teacherCourse/examAddOneQuestion.vue'
import KnowledgeAddMultiQues from '@/components/teacherCourse/knowledgeAddMultiQues.vue'

const { cookies } = useCookies()

//分页查询跳转回来后的已被选择的选项
const questionTable = ref(null)

const activeSections = ref(['query'])
const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(0)
const questions = ref([])

// 编辑弹窗
const editDialogVisible = ref(false)
const editForm = ref({
  id: null,
  subject: '',
  type: 1,
  remark: '',
  content: '',
  score: 0
})

// 添加模式
const mode = ref('single')

// 生成试卷模式
const isSelecting     = ref(false)
const selectedForPaper = ref([])
const isJumping = ref(false)

// 已选中的题目ID与文本框绑定
const selectedIds = computed(() => selectedForPaper.value.map(item => item.id).join(','))

// 新增预览对话框及生成结果
const previewDialogVisible = ref(false)
const generatedPaperId      = ref(null)

function typeLabel(t) {
  return t === 0 ? '填空题' : t === 1 ? '选择题' : '判断题'
}

async function fetchQuestions() {
  isJumping.value = true
  const res = await axios.get('/api/question/page', {
    params: { pageNum: pageNum.value, pageSize: pageSize.value }
  })
  if (res.data?.code === 200) {
    total.value = res.data.data.total
    questions.value = res.data.data.records.map(r => ({
      id: r.id,
      subject: r.subject,
      type: r.type,
      remark: r.remark,
      content: r.content,
      score: r.score
    }))
    
    await nextTick()
    await new Promise(r => setTimeout(r, 100))

    // console.log(selectedForPaper.value)
    // 先清空当前表格的勾选状态
    if(questions.value.length > 0){
      questionTable.value.clearSelection()
    }

    // 再对所有全局已选项做回填
    selectedForPaper.value.forEach(sel => {
        const row = questions.value.find(q => q.id === sel.id)
        if (row) {
            questionTable.value.toggleRowSelection(row, true)
        }
    })
  }
}

const showAItext = ref(false)
const AItext = ref('')
const showOverlay = ref(false) //缓冲图片
async function AIgenerateQuestion(){
  mode.value = 'ai_mode'
  if(AItext.value.length <= 0){
    alert('请输入题目的知识范围')
    return
  }
  showOverlay.value = true
  cookies.set('isWaitingAIQuestion', true)
  const res = await axios.post(`/api/question/add/ai?topic=${AItext.value}`)
  if(res.data?.code == 200){
    alert('生成题目完成')
    cookies.remove('isWaitingAIQuestion')
    showOverlay.value = false
    showAItext.value = false
  }
  if(res.data?.code == 500){
    cookies.remove('isWaitingAIQuestion')
    showOverlay.value = false
    showAItext.value = false
  }
  cookies.remove('isWaitingAIQuestion')
  showOverlay.value = false
  showAItext.value = false
}

function startSelecting() {
  // 切换到“在题库中选择”模式，展开查询部分
  isSelecting.value    = true
  activeSections.value = ['query', 'paper']
}

function openEditDialog(row) {
  Object.assign(editForm.value, row)
  editDialogVisible.value = true
}

function cancelSelecting() {
  isSelecting.value     = false
  selectedForPaper.value = []
  // 收起查询部分，只保留最初
  activeSections.value = []
}


// 勾选状态改变时同步 selectedForPaper
async function onSelectionChange(rows) {
  await new Promise(r => setTimeout(r, 100))
  // 当前页所有题目的 ID
  const currentPageIds = questions.value.map(q => q.id);

  // 1. 只保留 selectedForPaper 中，当前页已选的数据
  //    保留当前页已勾选的项，同时保留跨页勾选的项
  console.log("premir")
  console.log(selectedForPaper.value)
  if(isJumping.value){
    isJumping.value = false
  }
  else{
    selectedForPaper.value = selectedForPaper.value.filter(item => {
      // 保留不在当前页的项
      if (!currentPageIds.includes(item.id)) {
        return true;
      }
      // 在当前页，只保留已选中的项
      return rows.some(r => r.id === item.id);
    });
  }

  // 2. 现在，更新 selectedForPaper，保留已选项并加入当前页新选中的项
  rows.forEach(r => {
    // 如果当前页选中的项不在 selectedForPaper 中，添加进去
    if (!selectedForPaper.value.some(item => item.id === r.id)) {
      selectedForPaper.value.push(r);
    }
  });
}

async function saveEdit() {
  // TODO 调用更新接口
  // await axios.post('/api/question/update', editForm.value)
  editDialogVisible.value = false
}

// 生成试卷
async function generatePaper() {
  try {
    // 准备 id 列表
    const ids = selectedForPaper.value.map(q => q.id)
    // 发送生成请求
    const res = await axios.post('/api/paper/generate', ids)
    if (res.data?.code === 200) {
      generatedPaperId.value = res.data.data
      // 关闭预览窗
      previewDialogVisible.value = false
      // 这里可以选择清空 selectedForPaper 或保留
    } else {
      throw new Error(res.data.msg || '生成失败')
    }
  } catch (err) {
    console.error('生成试卷出错', err)
    // 你可以加一个提示：ElMessage.error(...)
  }
}

onMounted( async ()=>{
  fetchQuestions()
  if(cookies.isKey('isWaitingAIQuestion'))
    showOverlay.value = true
})

</script>

<style scoped>
.question-bank {
  padding: 20px;
  background: hsla(216, 33%, 97%, 0.6);
}
.query-form {
  margin-bottom: 10px;
  margin-top: 10px;
}
.pager {
  text-align: center;
  margin: 16px 0;
}
.add-buttons {
  margin-bottom: 16px;
}
.add-buttons .el-button {
  margin-right: 12px;
}
.add-content {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  justify-content: center;
}
.selectable-row {
  cursor: pointer;
}
.mb-4 {
  margin-bottom: 16px;
}
.ai-area {
  width: 80%;
}
.ai-area .el-input {
  width: 50%;
}
.ai-area .el-button {
  margin-left: 20px;
}

.loader-box {
  width: 200px;
  height: 200px;
  background-color: #753;
}

.loader {
  width: 48px;
  height: 48px;
  border: 4px solid #e5e7eb; /* 灰色 */
  border-top-color: #3b82f6;  /* 蓝色 */
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>
